Page({
  data: {
    currentIndex: 0,
    isRecording: false,
    sentences: [
      {
        id: 1,
        text: "How are you today?",
        translation: "你今天好吗？",
        audioUrl: "https://dict.youdao.com/dictvoice?audio=How are you today&type=1"
      },
      {
        id: 2,
        text: "Nice to meet you.",
        translation: "很高兴见到你。",
        audioUrl: "https://dict.youdao.com/dictvoice?audio=Nice to meet you&type=1"
      },
      {
        id: 3,
        text: "What's your name?",
        translation: "你叫什么名字？",
        audioUrl: "https://dict.youdao.com/dictvoice?audio=What's your name&type=1"
      }
    ],
    recorderManager: null,
    innerAudioContext: null
  },

  onLoad() {
    // 初始化录音管理器
    this.recorderManager = wx.getRecorderManager();
    this.innerAudioContext = wx.createInnerAudioContext();

    // 监听录音结束事件
    this.recorderManager.onStop((res) => {
      const { tempFilePath } = res;
      this.evaluateRecording(tempFilePath);
    });
  },

  // 播放示例音频
  playAudio() {
    const { sentences, currentIndex } = this.data;
    this.innerAudioContext.src = sentences[currentIndex].audioUrl;
    this.innerAudioContext.play();
  },

  // 开始录音
  startRecording() {
    // 先检查是否已经授权
    wx.getSetting({
      success: (res) => {
        if (res.authSetting['scope.record']) {
          // 已经授权，直接开始录音
          this.beginRecording();
        } else {
          // 未授权，请求授权
          wx.authorize({
            scope: 'scope.record',
            success: () => {
              // 用户同意授权，开始录音
              this.beginRecording();
            },
            fail: () => {
              // 用户拒绝授权，引导用户开启录音权限
              wx.showModal({
                title: '需要录音权限',
                content: '请允许小程序使用录音功能，以便进行语音评测',
                success: (res) => {
                  if (res.confirm) {
                    wx.openSetting({
                      success: (settingRes) => {
                        if (settingRes.authSetting['scope.record']) {
                          this.beginRecording();
                        }
                      }
                    });
                  }
                }
              });
            }
          });
        }
      }
    });
  },

  // 实际开始录音的方法
  beginRecording() {
    this.setData({ isRecording: true });
    this.recorderManager.start({
      duration: 10000,
      sampleRate: 16000,
      numberOfChannels: 1,
      encodeBitRate: 48000,
      format: 'mp3'
    });
  },

  // 停止录音
  stopRecording() {
    this.setData({ isRecording: false });
    this.recorderManager.stop();
  },

  // 评估录音（这里需要接入语音评测API）
  evaluateRecording(audioFile) {
    // 这里应该调用语音评测API
    // 为了演示，我们使用随机结果
    const score = Math.random() * 100;
    
    if (score > 80) {
      wx.showModal({
        title: '太棒了！',
        content: '发音非常标准，得分：' + score.toFixed(1),
        showCancel: false,
        success: () => {
          if (this.data.currentIndex < this.data.sentences.length - 1) {
            this.setData({
              currentIndex: this.data.currentIndex + 1
            });
          } else {
            wx.showToast({
              title: '恭喜完成所有练习！',
              icon: 'success'
            });
          }
        }
      });
    } else {
      wx.showModal({
        title: '继续加油！',
        content: '发音得分：' + score.toFixed(1) + '\n建议再练习一下哦',
        showCancel: false
      });
    }
  }
}); 